package com.org.oracle.service.impl;

import com.org.oracle.mongodb.entity.AiHistory;
import com.org.oracle.mongodb.vo.AiHistoryVO;
import com.org.oracle.mysql.dto.AiHistoryQueryDTO;
import com.org.oracle.service.AIService;
import com.org.oracle.service.TopicService;
import com.org.oracle.sub.entity.Message;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: heiye
 * @date: 2024/11/11 下午6:53
 * @version: v1.0.0
 * @description: AI转接ServiceImpl
 */
@Service
public class AIServiceImpl implements AIService {


    @Resource
    private TopicService topicService;
    @Resource
    private MongoTemplate mongoTemplate;


    @Override
    public void save(AiHistory aiHistory) {
        mongoTemplate.insert(aiHistory);
    }

    @Override
    public List<AiHistoryVO> historyList(AiHistoryQueryDTO aiHistoryQueryDTO) {
        Query query = new Query();
        query.addCriteria(Criteria.where("uid").is(aiHistoryQueryDTO.getUid()));
        query.addCriteria(Criteria.where("TopicId").is(aiHistoryQueryDTO.getTopicId()));
        List<AiHistory> aiHistories = mongoTemplate.find(query, AiHistory.class);
        List<AiHistoryVO> aiHistoryVOList =new ArrayList<>();
        for (AiHistory aiHistory : aiHistories) {
            AiHistoryVO historyVO = new AiHistoryVO();
            Message message = aiHistory.getMessages().get(aiHistory.getMessages().size() - 1);
            //拿最后一句话作为历史记录的提示
            historyVO.setInduction(message.getContent());
            historyVO.setMid(aiHistory.get_id());
            historyVO.setTopic(topicService.findHistoryVOById(aiHistory.getTopicId()));
            aiHistoryVOList.add(historyVO);
        }
        return aiHistoryVOList;
    }

    @Override
    public AiHistory historyDetail(String mid) {
        //TODO 布隆找聊天记录 目前没设计完就先不做了

        //MongoDB去找聊天记录
        Query query = new Query();
        //添加筛选 条件
        query.addCriteria(Criteria.where("_id").is(mid));
        return mongoTemplate.findOne(query, AiHistory.class);
    }
}
